package com.anpy.security.service;

import com.anpy.security.dto.JwtResponse;
import com.anpy.security.dto.LoginRequest;
import com.anpy.security.entity.Platform;
import com.anpy.security.repository.PlatformRepository;
import com.anpy.security.security.JwtTokenProvider;
import com.anpy.security.security.PlatformContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider tokenProvider;
    
    @Autowired
    private PlatformRepository platformRepository;

    /**
     * Authenticate user and generate JWT token
     * 
     * @param loginRequest Login request with username, password and platform code
     * @return JWT response with token and user details
     */
    public JwtResponse authenticateUser(LoginRequest loginRequest) {
        // Verify platform exists
        Platform platform = platformRepository.findByCode(loginRequest.getPlatformCode())
                .orElseThrow(() -> new RuntimeException("Platform not found: " + loginRequest.getPlatformCode()));
        
        // Set platform context for this authentication
        PlatformContextHolder.setPlatformCode(loginRequest.getPlatformCode());
        
        try {
            // Create authentication username in format: username@platformCode
            String usernameWithPlatform = loginRequest.getUsername() + "@" + loginRequest.getPlatformCode();
            
            // Authenticate against Spring Security
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            usernameWithPlatform,
                            loginRequest.getPassword()
                    )
            );
            
            // Set authentication in security context
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // Generate JWT token
            String jwt = tokenProvider.generateToken(authentication);
            
            // Extract user details and roles
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            List<String> roles = userDetails.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toList());
            
            // Return JWT response
            return new JwtResponse(jwt, loginRequest.getUsername(), loginRequest.getPlatformCode(), roles);
        } finally {
            // Clear platform context
            PlatformContextHolder.clear();
        }
    }
}
